const {
  Service,
} = require('uni-cloud-router')
const {
  TaskType,
} = require('../constants/const')
const {
  generateToken,
} = require('../utils/Auth')
const { getDate } = require('../utils/Date')
const ResponseUtil = require('../utils/Response')

module.exports = class ChildService extends Service {
  async list(data) {
    const { openId } = data
    console.log('openId', openId)
    const child = await this.db.collection('child').where({
      parent: openId,
    }).get()

    return ResponseUtil.success(child.data.map((item) => {
      return {
        id: item._id,
        parentId: item.parent,
        name: item.name,
        score: item.score,
      }
    }))
  }

  async add(data) {
    const { openId, id, name } = data
    const child = this.db.collection('child')

    const queryResult = child.where({
      parent: openId,
    })
    const count = await queryResult.count()

    if (count.total > 3) {
      return ResponseUtil.error('最多创建3个子女')
    }

    if (id) {
      child.where({
        id,
      }).update({
        name,
      })
    }
    else {
      child.add({
        parent: openId,
        name,
        score: 0,
      })
    }

    return ResponseUtil.success(null, '成功')
  }

  async remove(data) {
    const { openId, id } = data

    // 事务
    const transaction = await this.db.startTransaction()

    console.log('this.db.startTransaction', transaction)

    try {
      const submitPromise = []

      // 删除孩子表中的数据
      await transaction.collection('child').doc(id).remove()

      // 删除任务表中child的关联数据
      const tasks = await this.db.collection('task_templates').where({
        createdBy: openId,
      }).get()

      tasks.data.map((item) => {
        const promise = transaction.collection('task_templates').doc(item._id).update({
          children: item.children?.filter(i => i !== id),
        })
        submitPromise.push(promise)
        return promise
      })

      // 删除任务记录中child的管理数据
      const records = await this.db.collection('daily_task_records').where({
        childId: id,
        recordDate: getDate(),
      }).get()

      records.data.map((item) => {
        const promise = transaction.collection('daily_task_records').doc(item._id).remove()
        submitPromise.push(promise)
        return promise
      })

      await Promise.all(submitPromise)

      await transaction.commit()

      return ResponseUtil.success(null, '删除成功')
    }
    catch (err) {
      transaction.rollback()
      console.error('删除孩子失败', err)
      return ResponseUtil.error('删除失败')
    }
  }
}
